export function useRemLayout(options = {}) {
  const { clientWidth = 1920, base = 100, event = "resize" } = options;

  const docEl = document.documentElement;
  const originSize = docEl.fontSize;

  function resize() {
    let _clientWidth = docEl.clientWidth;

    if (!_clientWidth) return;
    if (_clientWidth > clientWidth) {
      _clientWidth = clientWidth;
    }

    const scale = _clientWidth / clientWidth;
    // eslint-disable-next-line no-mixed-operators
    docEl.style.fontSize = base * scale + "px";
  }

  function stopObserverSize() {
    if (!originSize) {
      document.getElementsByTagName("html")[0].style.fontSize = "";
    } else {
      document.documentElement.style.fontSize = originSize + "px";
    }

    window?.removeEventListener(event, resize);
  }

  function observerSize(handler = () => {}) {
    resize();
    window?.addEventListener(event, resize, false);
    if (typeof handler === "function") {
      handler();
    }

    return stopObserverSize;
  }

  return { observerSize, stopObserverSize };
}
